"use client"

import React, { createContext, useContext, useState } from 'react'
import { AlertTriangle, X } from 'lucide-react'
import { Button } from './button'

// 确认对话框配置
export interface ConfirmOptions {
  title?: string
  message: string
  confirmText?: string
  cancelText?: string
  type?: 'warning' | 'danger' | 'info'
  onConfirm?: () => void | Promise<void>
  onCancel?: () => void
}

// Confirm Context
interface ConfirmContextType {
  confirm: (options: ConfirmOptions) => Promise<boolean>
}

const ConfirmContext = createContext<ConfirmContextType | null>(null)

// Confirm Provider组件
export function ConfirmProvider({ children }: { children: React.ReactNode }) {
  const [isOpen, setIsOpen] = useState(false)
  const [options, setOptions] = useState<ConfirmOptions | null>(null)
  const [resolvePromise, setResolvePromise] = useState<((value: boolean) => void) | null>(null)

  const confirm = (options: ConfirmOptions): Promise<boolean> => {
    return new Promise((resolve) => {
      setOptions(options)
      setResolvePromise(() => resolve)
      setIsOpen(true)
    })
  }

  const handleConfirm = async () => {
    setIsOpen(false)
    if (options?.onConfirm) {
      try {
        await options.onConfirm()
      } catch (error) {
        console.error('Confirm action failed:', error)
      }
    }
    if (resolvePromise) {
      resolvePromise(true)
    }
    setOptions(null)
    setResolvePromise(null)
  }

  const handleCancel = () => {
    setIsOpen(false)
    if (options?.onCancel) {
      options.onCancel()
    }
    if (resolvePromise) {
      resolvePromise(false)
    }
    setOptions(null)
    setResolvePromise(null)
  }

  return (
    <ConfirmContext.Provider value={{ confirm }}>
      {children}
      <ConfirmDialog
        isOpen={isOpen}
        options={options}
        onConfirm={handleConfirm}
        onCancel={handleCancel}
      />
    </ConfirmContext.Provider>
  )
}

// useConfirm hook
export function useConfirm() {
  const context = useContext(ConfirmContext)
  if (!context) {
    throw new Error('useConfirm must be used within a ConfirmProvider')
  }
  return context.confirm
}

// 确认对话框组件
interface ConfirmDialogProps {
  isOpen: boolean
  options: ConfirmOptions | null
  onConfirm: () => void
  onCancel: () => void
}

function ConfirmDialog({ isOpen, options, onConfirm, onCancel }: ConfirmDialogProps) {
  if (!isOpen || !options) return null

  const getTypeConfig = () => {
    switch (options.type) {
      case 'danger':
        return {
          iconColor: 'text-red-600',
          iconBg: 'bg-red-100',
          confirmButtonClass: 'bg-red-600 hover:bg-red-700 focus:ring-red-500'
        }
      case 'warning':
        return {
          iconColor: 'text-yellow-600',
          iconBg: 'bg-yellow-100',
          confirmButtonClass: 'bg-yellow-600 hover:bg-yellow-700 focus:ring-yellow-500'
        }
      case 'info':
      default:
        return {
          iconColor: 'text-blue-600',
          iconBg: 'bg-blue-100',
          confirmButtonClass: 'bg-blue-600 hover:bg-blue-700 focus:ring-blue-500'
        }
    }
  }

  const typeConfig = getTypeConfig()

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto">
      {/* 背景遮罩 */}
      <div className="fixed inset-0 bg-black bg-opacity-50 transition-opacity" onClick={onCancel} />
      
      {/* 对话框容器 */}
      <div className="flex min-h-full items-center justify-center p-4">
        <div className="relative transform overflow-hidden rounded-lg bg-white shadow-xl transition-all sm:w-full sm:max-w-lg">
          {/* 关闭按钮 */}
          <button
            onClick={onCancel}
            className="absolute right-4 top-4 text-gray-400 hover:text-gray-600 focus:outline-none"
          >
            <X className="h-5 w-5" />
          </button>

          {/* 内容区域 */}
          <div className="px-6 py-6">
            <div className="flex items-start space-x-4">
              {/* 图标 */}
              <div className={`flex-shrink-0 flex items-center justify-center w-12 h-12 rounded-full ${typeConfig.iconBg}`}>
                <AlertTriangle className={`h-6 w-6 ${typeConfig.iconColor}`} />
              </div>

              {/* 文本内容 */}
              <div className="flex-1 mt-1">
                {options.title && (
                  <h3 className="text-lg font-medium text-gray-900 mb-2">
                    {options.title}
                  </h3>
                )}
                <p className="text-sm text-gray-600">
                  {options.message}
                </p>
              </div>
            </div>
          </div>

          {/* 按钮区域 */}
          <div className="bg-gray-50 px-6 py-4 flex justify-end space-x-3">
            <Button
              variant="outline"
              onClick={onCancel}
            >
              {options.cancelText || '取消'}
            </Button>
            <Button
              className={`text-white focus:ring-2 focus:ring-offset-2 ${typeConfig.confirmButtonClass}`}
              onClick={onConfirm}
            >
              {options.confirmText || '确认'}
            </Button>
          </div>
        </div>
      </div>
    </div>
  )
}